package sistemadeproyectos;

import java.sql.*;
import javax.swing.JOptionPane;
import javax.swing.ImageIcon;
import java.awt.FocusTraversalPolicy;
import java.awt.Component;
import java.awt.Container;
import java.awt.Image;
import java.util.ArrayList;

public class InicioSesion extends javax.swing.JFrame {

    private ImageIcon ajustarImagen(String ico, int ancho, int alto) {
        ImageIcon tmpIconAux = new ImageIcon(ico);
        //Escalar Imagen
        ImageIcon tmpIcon = new ImageIcon(tmpIconAux.getImage().getScaledInstance(ancho, alto, Image.SCALE_DEFAULT));
        return tmpIcon;
    }
    
    private void mostrarImagen(String imagen){
        if(System.getProperty("os.name").substring(0,5).equals("Windo")){
            jlblImagen.setIcon(ajustarImagen(System.getProperty("user.dir") + "\\src\\sistemadeproyectos\\images\\" + imagen + ".jpg", jlblImagen.getWidth(), jlblImagen.getHeight()));
        }
        else if(System.getProperty("os.name").substring(0,5).equals("Linux")){
            jlblImagen.setIcon(ajustarImagen(System.getProperty("user.dir") + "/src/sistemadeproyectos/images/" + imagen + ".jpg", jlblImagen.getWidth(), jlblImagen.getHeight()));
        }
    }
    
    /** Creates new form InicioSesion */
    public InicioSesion() {
        this.setSize(530, 199);
        initComponents();
        this.getRootPane().setDefaultButton(jbtnIniciarSesion);
        IndexedFocusTraversalPolicy policy = new IndexedFocusTraversalPolicy();
        policy.addIndexedComponent(jtxtUsuario);
        policy.addIndexedComponent(jpwfClave);
        policy.addIndexedComponent(jbtnIniciarSesion);
        policy.addIndexedComponent(jbtnRegistrarUsuario);
        policy.addIndexedComponent(jbtnCancelar);
        jtxtUsuario.requestFocus();
        this.setFocusTraversalPolicy(policy);
        mostrarImagen("Seguridad");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jbtnCancelar = new javax.swing.JButton();
        jbtnIniciarSesion = new javax.swing.JButton();
        jtxtUsuario = new javax.swing.JTextField();
        jpwfClave = new javax.swing.JPasswordField();
        jbtnRegistrarUsuario = new javax.swing.JButton();
        jlblImagen = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sistemadeproyectos.SistemadeproyectosApp.class).getContext().getResourceMap(InicioSesion.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        setResizable(false);

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jbtnCancelar.setText(resourceMap.getString("jbtnCancelar.text")); // NOI18N
        jbtnCancelar.setName("jbtnCancelar"); // NOI18N
        jbtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnCancelarActionPerformed(evt);
            }
        });

        jbtnIniciarSesion.setText(resourceMap.getString("jbtnIniciarSesion.text")); // NOI18N
        jbtnIniciarSesion.setName("jbtnIniciarSesion"); // NOI18N
        jbtnIniciarSesion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnIniciarSesionActionPerformed(evt);
            }
        });

        jtxtUsuario.setText(resourceMap.getString("jtxtUsuario.text")); // NOI18N
        jtxtUsuario.setName("jtxtUsuario"); // NOI18N

        jpwfClave.setText(resourceMap.getString("jpwfClave.text")); // NOI18N
        jpwfClave.setName("jpwfClave"); // NOI18N
        jpwfClave.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jpwfClaveFocusGained(evt);
            }
        });

        jbtnRegistrarUsuario.setText(resourceMap.getString("jbtnRegistrarUsuario.text")); // NOI18N
        jbtnRegistrarUsuario.setName("jbtnRegistrarUsuario"); // NOI18N
        jbtnRegistrarUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnRegistrarUsuarioActionPerformed(evt);
            }
        });

        jlblImagen.setText(resourceMap.getString("jlblImagen.text")); // NOI18N
        jlblImagen.setName("jlblImagen"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jlblImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jtxtUsuario, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jpwfClave, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(37, 37, 37))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbtnCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, 114, Short.MAX_VALUE)
                    .addComponent(jbtnIniciarSesion, javax.swing.GroupLayout.DEFAULT_SIZE, 114, Short.MAX_VALUE)
                    .addComponent(jbtnRegistrarUsuario, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 114, Short.MAX_VALUE))
                .addGap(24, 24, 24))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jlblImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jbtnIniciarSesion)
                                .addGap(18, 18, 18)
                                .addComponent(jbtnRegistrarUsuario)
                                .addGap(18, 18, 18)
                                .addComponent(jbtnCancelar))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jtxtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(25, 25, 25)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jpwfClave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(14, 14, 14)))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents


    private void jbtnIniciarSesionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnIniciarSesionActionPerformed
        // TODO add your handling code here:
        if ((jtxtUsuario.getText()).equals("") || (jpwfClave.getText()).equals("")) {
            JOptionPane.showMessageDialog(this, "Debe colocar un Nombre de Usuario y una Clave de Acceso" ,
               "Campos Vacíos", JOptionPane.WARNING_MESSAGE);
            jtxtUsuario.requestFocus();
        }
        else{
            BDAdmin motor = new BDAdmin("SELECT * FROM USUARIO WHERE NOMBRE = '"
              + jtxtUsuario.getText() + "' AND CLAVE = '" +jpwfClave.getText() + "'");
            try{
                ResultSet rs = motor.consulta();
                if(rs.next() == false) {
                    JOptionPane.showMessageDialog(this, "Clave o identificación de usuario inválida", 
                        "Inicio de Sesión Fallido", JOptionPane.ERROR_MESSAGE);
                    jpwfClave.selectAll();
                }
                else{
                    String avatar = rs.getString("URL_AVATAR");
                    JOptionPane.showMessageDialog(this, "Bienvenid@ al sistema " + rs.getString("nombre") + ".", 
                        "Acceso exitoso", JOptionPane.INFORMATION_MESSAGE);
                    motor.setQuery("SELECT * FROM PERTENECE WHERE USUARIO = '" + jtxtUsuario.getText() + "'");
                    rs = motor.consulta();
                    Usuario entrante = new Usuario();
                    entrante.setUsuario(jtxtUsuario.getText());
                    entrante.setClave(jpwfClave.getText());
                    entrante.setURL_Avatar(avatar);
                    if(rs.next() == true){
                        SeleccionarEquipo suEquipo = new SeleccionarEquipo();
                        suEquipo.setUsuario(entrante);
                        suEquipo.actualizar();
                        suEquipo.setVisible(true);
                        this.dispose();
                    }
                    else{
                        UnirseEquipo unir = new UnirseEquipo();
                        unir.setUsuario(entrante);
                        unir.setVisible(true);
                        this.dispose();
                    }
                }
                motor.cerrar();
            }
            catch(SQLException sqle){
                sqle.printStackTrace();
            }
        }
    }//GEN-LAST:event_jbtnIniciarSesionActionPerformed

    private void jbtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCancelarActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_jbtnCancelarActionPerformed

    private void jbtnRegistrarUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnRegistrarUsuarioActionPerformed
        // TODO add your handling code here:
        RegistrarUsuario usuario = new RegistrarUsuario(this,true);
        usuario.setVisible(true);
    }//GEN-LAST:event_jbtnRegistrarUsuarioActionPerformed

    private void jpwfClaveFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jpwfClaveFocusGained
        // TODO add your handling code here:
        jpwfClave.selectAll();
    }//GEN-LAST:event_jpwfClaveFocusGained

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new InicioSesion().setVisible(true);

            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JButton jbtnCancelar;
    private javax.swing.JButton jbtnIniciarSesion;
    private javax.swing.JButton jbtnRegistrarUsuario;
    private javax.swing.JLabel jlblImagen;
    private javax.swing.JPasswordField jpwfClave;
    private javax.swing.JTextField jtxtUsuario;
    // End of variables declaration//GEN-END:variables
}

 class IndexedFocusTraversalPolicy extends FocusTraversalPolicy {

   private ArrayList<Component> components = 
      new ArrayList<Component>();

   public void addIndexedComponent(Component component) {
        components.add(component);
   }

   @Override
   public Component getComponentAfter(Container aContainer, 
               Component aComponent) {
        int atIndex = components.indexOf(aComponent);
        int nextIndex = (atIndex + 1) % components.size();
        return components.get(nextIndex);
   }

   @Override
   public Component getComponentBefore(Container aContainer,
         Component aComponent) {
        int atIndex = components.indexOf(aComponent);
        int nextIndex = (atIndex + components.size() - 1) %
                components.size();
        return components.get(nextIndex);
   }

   @Override
   public Component getFirstComponent(Container aContainer) {
        return components.get(0);
   }
   
   @Override
   public Component getDefaultComponent(Container aConteiner){
       return null;
   }
   
   @Override
   public Component getLastComponent(Container aContainer){
       return null;
   }
}